
//
//  ChatManager.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/26.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "ChatManager.h"

@interface ChatManager () {


}

@property (nonatomic,strong)RecentChatManager *rcManager;

@end

@implementation ChatManager

+ (ChatManager*)sharedInstance {
    static dispatch_once_t onceBasicToken;
    
    static ChatManager *rcManager = nil;
    
    dispatch_once(&onceBasicToken, ^{
        rcManager = [[ChatManager alloc] init];
    });
    return rcManager;
}

/**
 @brief  根据storeId生成聊天表名
 @param  friendid 导购ID
 @return 用户聊天表名称
 */
- (NSString *)chatTableName:(NSString *)friendid {
    NSString *tableName = [NSString stringWithFormat:@"chat_%@", friendid];
    return tableName;
}

/**
 @brief 队列中创建聊天记录表并插入数据
 @param msg 会话消息
 */
- (BOOL)createChatTable:(ChatMessage *)msg
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *chatTableName = [self chatTableName:msg.toFriendid];
    
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ integer primary key AUTOINCREMENT not null,%@ varchar,%@ varchar,%@ integer,%@ varchar,%@ integer,%@ integer,%@ integer,%@ varchar,%@ varchar,%@ varchar,%@ integer,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar,%@ varchar)", chatTableName, Chat_dbId,Chat_msgId, Chat_sender, Chat_msgSourceType, Chat_msgContent, Chat_messageState, Chat_mediaStatus, Chat_messageBodyType, Chat_contentpath, Chat_voiceLength, Chat_mediaPath, Chat_readStatus, Chat_sendTime, Chat_splitTime,Chat_msgUrl,Chat_rawPrice,Chat_discountPrice,Chat_detailContent,Chat_userData];
    
    BOOL bol = [dbQueue.database executeStatements:sql];
    if (bol) {
        NSString *voiceDir = [FilePathMode getChatVoicePath:msg.toFriendid];
        NSString *imageDir = [FilePathMode getChatImagePath:msg.toFriendid];
        [FilePathMode createFileDirectory:voiceDir];
        [FilePathMode createFileDirectory:imageDir];
    }
    
    return bol;
}

#pragma mark - -------聊天记录表操作相关--------

/**
 @brief 插入多条消息数据到聊天界面
 @param listData 多条消息数据
 */
- (void)insertChatMsgWithList:(NSArray *)listData {
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
        for (ChatMessage *chatMsg in listData)
        {
            if (![self checkTableExist:chatMsg.toFriendid]) {
                break;
            }
            
            BOOL suc =  [self insertChatMessage:chatMsg];
            chatMsg.dbId = [NSString stringWithFormat:@"%lld", db.lastInsertRowId];
            if (!suc) {
                *rollback = YES;
                return;
            }
            suc = [self updateChatTableByDBID:chatMsg.dbId storeId:chatMsg.toFriendid withSplitTime:chatMsg.splitTime];
            if (!suc) {
                *rollback = YES;
                return;
            }
        }
        //成功之后
            ChatMessage *firstMsg = (ChatMessage *)[listData firstObject];
            RecentChat *rChat = nil;
            if (firstMsg) {
                rChat = [self updateOrInsertDataToRecent:firstMsg];
                firstMsg.splitTime = [self caclSplitTime:rChat.previousTime msgTime:firstMsg.sendTime];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (firstMsg.msgSourceType==CHAT_MSG_RECV)
                {
                  //发送通知，刷新界面
                }
            });
        
    }];
}



//插入数据
- (BOOL)insertChatMessage:(ChatMessage *)msg
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    NSString *chatTableName = [self chatTableName:msg.toFriendid];
    
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (%@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", chatTableName, Chat_msgId, Chat_sender, Chat_msgSourceType, Chat_msgContent, Chat_messageState, Chat_mediaStatus, Chat_messageBodyType, Chat_contentpath,Chat_voiceLength, Chat_mediaPath,Chat_readStatus,Chat_sendTime,Chat_splitTime,Chat_msgUrl,Chat_rawPrice,Chat_discountPrice,Chat_detailContent,Chat_userData];
    NSArray *array = [NSArray arrayWithObjects:
                      objectToString(msg.msgId),
                      objectToString(msg.sender),
                      @(msg.msgSourceType),
                      objectToString(msg.msgContent),
                      @(msg.messageState),
                      @(msg.mediaStatus),
                      @(msg.messageBodyType),
                      objectToString(msg.contentPath),
                      objectToString(msg.voiceLength),
                      objectToString(msg.mediaPath),
                      @(msg.readStatus),
                      objectToString(msg.sendTime),
                      objectToString(msg.splitTime),
                      objectToString(msg.msgUrl),
                      objectToString(msg.rawPrice),
                      objectToString(msg.discountPrice),
                      objectToString(msg.detailContent),
                      objectToString(msg.userData),
                      nil];
    
    BOOL bol = [(FMDatabase *)[dbQueue database] executeUpdate:sql withArgumentsInArray:array];

    return bol;
}



/**
 @brief  将消息插入消息记录表
 @param  msg 消息
 @return 查询到最近聊天消息
 */
- (RecentChat *)insertDataToChatMsgTable:(ChatMessage *)msg
{
    BOOL ret = NO;
    BOOL bol = NO;
    
    if (msg.msgSourceType == CHAT_MSG_SEND) {
        ret = NO;
    }
    else
    {
        ret = [self isExistChatMessageWithMsgId:msg.msgId storeId:msg.toFriendid];
    }
    
    RecentChat *rChat = nil;
    if (!ret) {
        bol = [self insertChatMessage:msg];
        
        if (bol) {
            
            BOOL updateUnread = ([rChat.updateTime caseInsensitiveCompare:msg.sendTime]== NSOrderedDescending);
            
            rChat = [self updateOrInsertDataToRecent:msg];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"postNotificationName ==> NewMessage");
                if (msg.msgSourceType==CHAT_MSG_RECV || msg.messageBodyType == ChatMsgBodyType_Commodity) {
                   //需要后期填充
                    
                    
                }
                
            });
        }
    }
    
    return rChat;
}


/**
 @brief  更新最近聊天消息
 @param  msg 消息
 @return 最近聊天消息
 */
- (RecentChat *)updateOrInsertDataToRecentAtQueue:(ChatMessage *)msg
{
    __block RecentChat *rChat;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        rChat = [self updateOrInsertDataToRecent:msg];
    }];
    
    return rChat;
}

// 更新最近聊天消息
- (RecentChat *)updateOrInsertDataToRecent:(ChatMessage *)msg
{
    
    RecentChat *recent = [self.rcManager selectRecentDataWithFriendid:msg.toFriendid];
    
    if (!recent) {
        recent = [[RecentChat alloc] init];
        recent.friendid = msg.toFriendid;
        recent.friendName = msg.toFriendName;
        recent.friendLogo = msg.toFriendLogo;
    }
    
    recent.previousTime = [NSString stringWithFormat:@"%@",recent.updateTime];
    
    if (msg.msgSourceType==CHAT_MSG_SEND) {
        recent.unreadCount = 0;
    }
    else
    {
        recent.unreadCount += ((msg.messageBodyType == ChatMsgBodyType_Service)?0:1);
        
        //如果是当前聊天画面则把未读消息设置为0，
        if ([[[UserManager shareInstance] currentChatId] isEqualToString:msg.toFriendid]) {
            recent.unreadCount = 0;
        }
    }

    recent.msgSourceType = msg.msgSourceType;
    recent.newerMsg = msg.msgContent;
    
    recent.displayMsg = [self convertMsgContentToDisplayMsg:msg.messageBodyType msgContent:msg.msgContent];
    
    recent.updateTime = msg.sendTime;
    recent.msgBodyType = msg.messageBodyType;
    recent.msgState = msg.messageState;
    
    __unused BOOL ret = [self.rcManager insertOrUpdateRecentWithData:recent];
    
    return recent;
}


/**
 @brief  将聊天记录插入到本地数据库
 @param  chatMsg 消息
 @return 消息
 */
- (ChatMessage *)insertChatMsgToChatTable:(ChatMessage *)chatMsg
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    if (![self checkTableExist:chatMsg.toFriendid]) {
        [self createChatTable:chatMsg];
        [self insertDataToChatMsgTable:chatMsg];
        chatMsg.splitTime = chatMsg.sendTime;
        chatMsg.dbId = @"1";
    }
    else
    {
        RecentChat *rChat = [self insertDataToChatMsgTable:chatMsg];
        
        if (!rChat) {
            return chatMsg;
        }
        chatMsg.splitTime = [self caclSplitTime:rChat.previousTime msgTime:chatMsg.sendTime];
        chatMsg.dbId = [NSString stringWithFormat:@"%lld", dbQueue.database.lastInsertRowId];
    }
    [self updateChatTableByDBID:chatMsg.dbId storeId:chatMsg.toFriendid withSplitTime:chatMsg.splitTime];
    
    return chatMsg;
}

/**
 @brief  队列中将聊天记录插入到本地数据库
 @param  chatMsg 消息
 @return 消息
 */
- (ChatMessage *)insertChatMsgToChatTableAtQueue:(ChatMessage *)chatMsg
{
    __block ChatMessage *chatMessage = chatMsg;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        chatMessage = [self insertChatMsgToChatTable:chatMessage];
    }];
    
    return chatMessage;
}


// 判断指定表是否存在
- (BOOL)checkTableExist:(NSString *)storeId
{
    __block BOOL result = NO;
    NSString *chatTableName = [self chatTableName:storeId];
    NSString* lowtableName = [chatTableName lowercaseString];
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    result = [dbQueue.database tableExists:lowtableName];
    return result;
}

// 在队列中判断指定表是否存在
- (BOOL)checkTableExistAtqueue:(NSString *)storeId
{
    __block BOOL isExist = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        isExist = [self checkTableExist:storeId];
    }];
    
    return isExist;
}

// 计算时间分割线
- (NSString*)caclSplitTime:(NSString*)refTime msgTime:(NSString*)msgTime
{
    //拿到session最后一条消息的serverTime，然后比较是否超过10分钟
    NSString* lastMsgTime = refTime;
    if(lastMsgTime==nil||[lastMsgTime isEqualToString:@""]||lastMsgTime.length<1)
    {
        //第一条消息，一定要有分割线
        return msgTime;
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *lastMsgDate = [dateFormatter dateFromString:lastMsgTime];
    NSTimeInterval last = [lastMsgDate timeIntervalSince1970];
    
    NSDate *nowMsgDate = [dateFormatter dateFromString:msgTime];
    NSTimeInterval now = [nowMsgDate timeIntervalSince1970];
    if(now-last>kIntervalOfShowTime)
    {
        return msgTime;
    }
    return @"";
}


/**
 @brief 通过数据库Id更新单条消息
 @param dbId 消息唯一标识符
 @param storeId 导购ID
 @param msg 消息
 */
- (BOOL)updateChatTableBy:(NSString *)dbId storeId:(NSString *)storeId message:(ChatMessage *)msg
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    NSString *chatTable = [self chatTableName:storeId];
    NSString *sql = [NSString stringWithFormat:@"update %@ set %@ = ?, %@ = ?, %@=?, %@ = ?, %@=?, %@ = ?, %@=?, %@ = ?, %@=?, %@ = ?, %@=?, %@ = ?, %@=?, %@ = ?, %@ = ?, %@ = ?, %@=?, %@=? where %@ = ?",chatTable,Chat_msgId, Chat_sender, Chat_msgSourceType, Chat_msgContent, Chat_messageState, Chat_mediaStatus, Chat_messageBodyType, Chat_contentpath,Chat_voiceLength, Chat_mediaPath,Chat_readStatus,Chat_sendTime,Chat_splitTime,Chat_msgUrl,Chat_rawPrice,Chat_discountPrice,Chat_detailContent,Chat_userData,Chat_dbId];
    
    NSArray *args = [NSArray arrayWithObjects:
                     objectToString(msg.msgId),
                     objectToString(msg.sender),
                     @(msg.msgSourceType),
                     objectToString(msg.msgContent),
                     @(msg.messageState),
                     @(msg.mediaStatus),
                     @(msg.messageBodyType),
                     objectToString(msg.contentPath),
                     objectToString(msg.voiceLength),
                     objectToString(msg.mediaPath),
                     @(msg.readStatus),
                     objectToString(msg.sendTime),
                     objectToString(msg.splitTime),
                     objectToString(msg.msgUrl),
                     objectToString(msg.rawPrice),
                     objectToString(msg.discountPrice),
                     objectToString(msg.detailContent),
                     objectToString(msg.userData),
                     dbId,nil];
    
    bol = [dbQueue.database executeUpdate:sql withArgumentsInArray:args];
    
    if (bol) {
        [self updateOrInsertDataToRecent:msg];
    }
    
    return bol;
}

/**
 @brief 通过数据库Id更新单条消息
 @param dbId 消息唯一标识符
 @param storeId 导购ID
 */
- (BOOL)updateChatTableAtQueueBy:(NSString *)dbId storeId:(NSString *)storeId message:(ChatMessage *)msg
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        bol = [self updateChatTableBy:dbId storeId:storeId message:msg];
    }];
    
    return bol;
}

/**
 @brief 通过dbId获取单条数据
 @param dbId 消息唯一标识符
 @param storeId 导购ID
 @param msg 消息
 */
- (ChatMessage *)selectChatMsgDataBy:(ChatMessage *)msg dbId:(NSString *)dbId storeId:(NSString *)storeId
{
    __block ChatMessage *chatMsg = nil;
    
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTableName = [self chatTableName:storeId];
        
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@='%@'", chatTableName, Chat_dbId, dbId];
        
        FMResultSet *result = [db executeQuery:sql];
        
        NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];
        while ([result next]) {
            ChatMessage *data = [ChatMessage ChatMessageDataFromDB:result];
            data.toFriendid = storeId;
            [tempArr addObject:data];
        }
        if (tempArr.count > 0) {
            chatMsg = tempArr[0];
        } else {
            [self createChatTable:msg];
            [self insertDataToChatMsgTable:msg];
        }
    }];

    return chatMsg;
}

#pragma mark - 查询

/**
 @brief 通过PacketId查询单条消息
 @param packetId 消息唯一标识符
 @param userId 用户Id
 */
- (BOOL)isExistChatMessageWithDBId:(NSString *)dbId storeId:(NSString *)storeId
{
    if ([dbId integerValue]<1 || dbId.length <1) {
        return NO;
    }
    
    NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    NSString *chatTableName = [self chatTableName:storeId];
    
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@='%@'", chatTableName, Chat_dbId, dbId];
    __block BOOL resu = NO;
    [dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        FMResultSet *result = [db executeQuery:sql];
        
        while ([result next]) {
            RecentChat *data = [RecentChat recentConcactDataFromDB:result];
            [tempArr addObject:data];
        }
        
        if (tempArr.count > 0) {
            resu = YES;
        }
    }];
    return resu;
}

/**
 @brief 通过msgId查询单条消息
 @param msgId 消息唯一标识符
 @param storeId 门店Id
 */
- (BOOL)isExistChatMessageWithMsgId:(NSString *)msgId storeId:(NSString *)storeId
{
    if (msgId.length<1) {
        return NO;
    }
    
    NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    NSString *chatTableName = [self chatTableName:storeId];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@='%@'", chatTableName, Chat_msgId, msgId];
    
    
    FMResultSet *result = [(FMDatabase *)[dbQueue database] executeQuery:sql];
    
    while ([result next]) {
        RecentChat *data = [RecentChat recentConcactDataFromDB:result];
        [tempArr addObject:data];
    }
    
    if (tempArr.count > 0) {
        return YES;
    }
    return NO;
}

/**
 @brief  队列中判断对应消息在消息记录表中存在
 @param  storeId  门店ID
 @param  msgBodyType  消息类型
 @return 是否存在记录
 */
- (BOOL)isExistChatMsgWithStoreIdAtQueue:(NSString *)storeId messageBodyType:(ChatMsgBodyType)msgBodyType
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        if ([self checkTableExist:storeId]) {
            NSString *chatTableName = [self chatTableName:storeId];
            
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = %d", chatTableName, Chat_messageBodyType, (int)msgBodyType];
            
            FMResultSet *result = [db executeQuery:sql];
            bol = [result next];
            
            [result close];
        }
    }];
    
    return bol;
}

#pragma mark - 获取
/**
 @brief 获取某条消息之前指定数量的消息
 @param storeId 导购ID
 @param count 数量
 */
- (NSArray *)selectDataFromTableBy:(NSString *)storeId currentCount:(NSInteger)count
{
    __block NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        if ([self checkTableExist:storeId])
        {
            NSString *chatTableName = [self chatTableName:storeId];
            NSString *sql = [NSString stringWithFormat:@"select * from %@", chatTableName];
            NSString *offset = [NSString stringWithFormat:@"((SELECT count(*) FROM %@) - %d - %d)", chatTableName, (int)count, kRecordPerPage];
            NSString *limit = [NSString stringWithFormat:@" LIMIT %d + min(0, %@) OFFSET %@", kRecordPerPage, offset, offset];
            sql = [sql stringByAppendingString:limit];
            
            FMResultSet *resulet = [db executeQuery:sql];
            
            while ([resulet next]) {
                
                ChatMessage *data = [ChatMessage ChatMessageDataFromDB:resulet];
                data.toFriendid = storeId;
                [tempArr addObject:data];
            }
        }
    }];
    
    return tempArr;
}


#pragma mark - 更新
/**
 @brief 通过dbId更新消息收发状态
 @param dbId 消息唯一标识符
 @param storeId 导购ID
 @param state 消息的状态
 */
- (BOOL)updateChatTableBy:(NSString *)dbId storeId:(NSString *)storeId messageState:(ChatMsgState)state
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTable = [self chatTableName:storeId];
        NSString *sql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",chatTable,Chat_messageState,Chat_dbId];
        NSArray *args = @[@(state),dbId];
        
        bol = [db executeUpdate:sql withArgumentsInArray:args];
    }];
    
    return bol;
}


- (BOOL)updateChatTableBy:(NSString *)dbId storeId:(NSString *)storeId mediaStatus:(ChatMsgMediaState)mediaStatus
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTable = [self chatTableName:storeId];
        NSString *sql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",chatTable,Chat_mediaStatus,Chat_dbId];
        NSArray *args = @[@(mediaStatus),dbId];
        
        bol = [db executeUpdate:sql withArgumentsInArray:args];
    }];
    
    return bol;
}


- (BOOL)updateChatTableBy:(NSString *)dbId storeId:(NSString *)storeId contentPath:(NSString*)contentPath
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *chatTable = [self chatTableName:storeId];
    NSString *sql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",chatTable,Chat_contentpath,Chat_dbId];
    NSArray *args = @[objectToString(contentPath),dbId];
    [dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        bol = [db executeUpdate:sql withArgumentsInArray:args];

    }];
    
    return bol;
}

- (BOOL)updateChatTableBy:(NSString *)dbId storeId:(NSString *)storeId voiceLength:(NSString*)voiceLength
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTable = [self chatTableName:storeId];
        NSString *sql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",chatTable,Chat_voiceLength,Chat_dbId];
        NSArray *args = @[objectToString(voiceLength),dbId];
        
        bol = [db executeUpdate:sql withArgumentsInArray:args];
    }];
    
    return bol;
}


/**
 @brief 通过PacketId更新消息送达的状态 (暂时不需要)
 @param contentPath 消息唯一标识符
 @param mediaStatus 消息的更新时间
 @param state 消息的状态
 */
- (BOOL)updateChatTableBy:(NSString *)dbId
                  storeId:(NSString *)storeId
              contentPath:(NSString*)contentPath
              mediaStatus:(ChatMsgMediaState)mediaStatus
             messageState:(ChatMsgState)state
{
    __block BOOL bol = NO;
    
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTable = [self chatTableName:storeId];
        
        NSString *sql = nil;
        NSArray *args = nil;
        
        if (contentPath.length) {
            sql = [NSString stringWithFormat:@"update %@ set %@ = ?,%@ = ?,%@ = ? where %@ = ?",chatTable,Chat_contentpath,Chat_mediaStatus,Chat_messageState,Chat_dbId];
            args = @[objectToString(contentPath),@(mediaStatus),@(state),dbId];
            
        }
        else
        {
            sql = [NSString stringWithFormat:@"update %@ set %@ = ?,%@ = ? where %@ = ?",chatTable,Chat_mediaStatus,Chat_messageState,Chat_dbId];
            args = @[@(mediaStatus),@(state),dbId];
        }
        
        bol = [db executeUpdate:sql withArgumentsInArray:args];
    }];
    
    return bol;
}

/**
 @brief 通过storeId更新接收到的语音消息的已读未读
 @param storeId 导购ID
 */
- (void)updateUnreadMessageToReadedWithStoreId:(NSString *)storeId
{
    
}

/**
 @brief 通过dbId和更新时间更新消息收发状态
 @param dbId 消息唯一标识符
 @param time 更新时间
 @param state 消息的状态
 */
- (void)updateChatTableBy:(NSString *)dbId withTime:(NSString *)time messageState:(ChatMsgState)state
{
    
}

/**
 @brief 通过dbId和storeId更新消息时间分割线
 @param dbId 消息唯一标识符
 @param storeId 导购ID
 @param splitTime 消息的状态
 */
- (BOOL)updateChatTableByDBID:(NSString *)dbId storeId:(NSString *)storeId withSplitTime:(NSString *)splitTime
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    NSString *chatTable = [self chatTableName:storeId];
    NSString *sql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",chatTable,Chat_splitTime,Chat_dbId];
    NSArray *args = @[objectToString(splitTime),dbId];
    bol = [dbQueue.database executeUpdate:sql withArgumentsInArray:args];
    return bol;
}

/**
 @brief  通过dbId和storeId更新消息阅读状态
 @param  dbId 消息唯一标识符
 @param storeId 导购ID
 @param  isVoiceReaded 消息是否阅读
 @return 更新操作是否成功
 */
- (BOOL)updateChatTableBy:(NSString *)dbId storeId:(NSString *)storeId isVoiceReaded:(BOOL)isVoiceReaded
{
    __block BOOL bol = NO;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTableName =  [self chatTableName:storeId];
        NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@=? WHERE %@=?", chatTableName, Chat_readStatus, Chat_dbId];
        NSArray *args = @[@((int)isVoiceReaded), objectToString(dbId)];
        bol = [db executeUpdate:sql withArgumentsInArray:args];
    }];
    
    return bol;
}

#pragma mark - 获取
/**
 @brief  通过storeId查询对应聊天的全部图片
 @param  storeId 导购ID
 @param  mType 消息类型
 @return 图片数组
 */
- (NSArray *)selectImageArray:(NSString *)storeId messageBodyType:(ChatMsgBodyType)mType
{
    __block NSMutableArray *imageArr = [NSMutableArray arrayWithCapacity:0];
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
        
        NSString *tableName = [self chatTableName:storeId];
        NSString *sql = [NSString stringWithFormat:@"SELECT %@ FROM %@ WHERE %@=%d and (%@ = %d or %@ = %d)", Chat_contentpath, tableName, Chat_messageBodyType,(int)ChatMsgBodyType_Image,Chat_mediaStatus,(int)MEDIA_DOWNLOAD_SUCC,Chat_msgSourceType,(int)CHAT_MSG_SEND];
        
        FMResultSet *resulet = [db executeQuery:sql];
        
        while ([resulet next]) {
            NSString *str = [resulet stringForColumn:Chat_contentpath];
            [imageArr addObject:str];
        }
    }];
    
    return imageArr;
}
/**
 @brief 根据storeId删除某个客户的聊天记录
 @param  storeId 导购ID
 */
- (void)deleteChatTable:(NSString *)storeId
{
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *tableName = [self chatTableName:storeId];
        if ([self checkTableExist:tableName]) {
            NSString *sql = [NSString stringWithFormat:@"DROP TABLE %@",tableName];
            [db executeUpdate:sql];
        }
    }];
}


#pragma mark - 私有方法
/**
 *  @brief 转换成实际显示内容
 *  @param mType 聊天信息类型
 *  @param content 聊天信息内容
 */
- (NSString *)convertMsgContentToDisplayMsg:(ChatMsgBodyType)mType msgContent:(NSString *)content
{
    NSString *displayMsg = nil;
    switch (mType) {
        case ChatMsgBodyType_Text:
            displayMsg = content;
            break;
        case ChatMsgBodyType_Image:
            displayMsg = @"[图片]";
            break;
        case ChatMsgBodyType_Voice:
            displayMsg = @"[语音]";
            break;
        case ChatMsgBodyType_Video:
            displayMsg = @"[视频]";
            break;
        case ChatMsgBodyType_Location:
            displayMsg = @"[位置]";
            break;
        case ChatMsgBodyType_File:
            displayMsg = @"[文件]";
            break;
            
        case ChatMsgBodyType_PicAndText:
        case ChatMsgBodyType_Commodity:
            displayMsg = @"[图文消息]";
            break;
        case ChatMsgBodyType_Service:
            displayMsg = @"[服务]";
            break;
            
        default:
            break;
    }
    
    return displayMsg;
}



/**
 @brief  查询客户总的消息条数
 @return 消息条数
 */
- (int)selectTotalChatMsgCountByFriendid:(NSString *)friendid
{
    __block int count = 0;
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    
    [dbQueue inDatabase:^(FMDatabase *db) {
        NSString *chatTableName = [self chatTableName:friendid];
        
        NSString *sql = [NSString stringWithFormat:@"select count(*) from %@ where %@ = %d ",chatTableName,Chat_msgSourceType,(int)CHAT_MSG_RECV];
        FMResultSet *rs = [db executeQuery:sql];
        if ([rs next]) {
            count = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return count;
}


#pragma mark - getter 
- (RecentChatManager *)rcManager {
    if (_rcManager == nil) {
        _rcManager = [RecentChatManager sharedInstance];
    }
    return _rcManager;
}

#pragma mark - public
/**
 *  @brief 发送消息前先保存聊天信息
 *  @param contentType 消息类型
 *  @param msgContent  消息内容
 *  @param contentPath 内容路径
 *  @param voiceLength 文件长度
 *  @param rChat  最近聊天记录
 *  @return 聊天消息
 */
- (ChatMessage *)saveChatMessage:(ChatMsgBodyType)contentType
                      msgContent:(NSString *)msgContent
                     contentPath:(NSString *)contentPath
                     voiceLength:(NSString *)voiceLength
                      recentChat:(RecentChat *)rChat
{
    //保存消息
    ChatMessage *chatMsg =[[ChatMessage alloc] init];
    
    // 时间戳
    chatMsg.msgId = [DateConvert getCurrentTimeInterval];
    
    chatMsg.sender= [[UserManager shareInstance] getUserId];
    
    chatMsg.sendTime = [DateConvert getSystemDatetime];
    chatMsg.toFriendid = rChat.friendid;
    chatMsg.toFriendName = rChat.friendName;
    chatMsg.toFriendLogo = rChat.friendLogo;
    
    if(contentType==ChatMsgBodyType_Text)
    {
        chatMsg.msgContent = msgContent;
    }
    else if(contentType==ChatMsgBodyType_Image)
    {
        //图片，content是Image路径
        chatMsg.contentPath = contentPath;//本地path,相对路径
        chatMsg.mediaStatus = MEDIA_DOWNLOAD_SUCC;
    }
    else if(contentType==ChatMsgBodyType_Voice)
    {
        //音频，content是voice路径
        chatMsg.contentPath = contentPath;//本地path
        chatMsg.voiceLength = voiceLength;//音频时长
    }
    chatMsg.msgSourceType = CHAT_MSG_SEND;
    
    chatMsg.messageBodyType = contentType;
    
    chatMsg.messageState = CHAT_MSG_SENDING;
    
    chatMsg.readStatus = CHAT_MSG_READED;
    
    chatMsg = [self insertChatMsgToChatTableAtQueue:chatMsg];
    
    return chatMsg;
}


@end
